package com.example.testdemo.service;

import com.example.testdemo.Dao.bookDao;
import com.example.testdemo.pojo.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class bookService {
    public static List<Book> getallBooks() throws SQLException, ClassNotFoundException {
        Connection connection = bookDao.connection();
        String sql = "select * from  book";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        List<Book> list = new ArrayList<Book>();
        while (rs.next()){
            Book book = new Book();
            book.setIsbn(rs.getString("isbn"));
            book.setBname(rs.getString("bname"));
            book.setBauther(rs.getString("bauther"));
            book.setBnumber(rs.getString("bnumber"));
            book.setPrice(rs.getString("price"));
            list.add(book);
        }
        return list;
    }

    public static Book query(String isbn) throws SQLException, ClassNotFoundException {
        Connection connection = bookDao.connection();
        String sql = "select * from book where isbn = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,isbn);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            Book book = new Book();
            book.setIsbn(isbn);
            book.setBname(rs.getString("bname"));
            book.setBauther(rs.getString("bauther"));
            book.setBnumber(rs.getString("bnumber"));
            book.setPrice(rs.getString("price"));
            return book;
        }
        return null;
    }

    public static int add(String isbn,String bname,String bauther,String bnumber,String price) throws SQLException, ClassNotFoundException {
        Connection connection = bookDao.connection();
        String sql = "insert into book (isbn,bname,bauther,bnumber,price) values(?,?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,isbn);
        ps.setString(2,bname);
        ps.setString(3,bauther);
        ps.setString(4,bnumber);
        ps.setString(5,price);
        return ps.executeUpdate();
    }

    public static int deletebook(String isbn) throws SQLException, ClassNotFoundException {
        Connection connection = bookDao.connection();
        String sql = "delete from book where isbn = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,isbn);
        return ps.executeUpdate();
    }


}
